package com.example.demo.netty.chat_room.server;

import com.example.demo.netty.chat_room.util.MessageDecoder;
import com.example.demo.netty.chat_room.util.MessageEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class ChatServer {
    public static void main(String[] args) {
        // 获得线程组
        EventLoopGroup bossGroup= new NioEventLoopGroup(1);
        EventLoopGroup workGroup= new NioEventLoopGroup(10);

        try {
            // 各种配置
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {

                            socketChannel.pipeline()
                                    // 字符串编解码
//                                    .addLast(new StringDecoder())
//                                    .addLast(new StringEncoder())
                                    // 解码器
                                    .addLast(new MessageDecoder())
                                    // 编码器
                                    .addLast(new MessageEncoder())
                                    .addLast(new ServerHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 记得关闭资源
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }


    }
}
